/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.compomics.fastagenerator.fastagrabber;

import com.compomics.fastagenerator.fastagrabber.consoleformatter.Spinner;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;

/**
 *
 * @author Kenneth
 */
public class FastaComposer {

    private static File outputFile;
    private static FastaComposer composer;
    private static BufferedWriter out;

    private FastaComposer() {
    }

    public static FastaComposer getInstance(File outputFile) throws IOException {
        FastaComposer.outputFile = outputFile;
        out = new BufferedWriter(new FileWriter(outputFile), 1024 * 8);
        if (composer == null) {
            composer = new FastaComposer();
        }
        return composer;
    }

    public void writeToFasta(List<String> fastaLines) {
        try {
            // Create file 
            for (String line : fastaLines) {
                if (!line.isEmpty() && line != null) {
                    out.write(line);
                    out.flush();
                }
            }
            //Close the output stream
        } catch (Exception e) {//Catch exception if any
            e.printStackTrace();
            System.err.println("Error: " + e.getMessage());
        }
    }

    public void finalize() throws FileNotFoundException, IOException {
        if (outputFile.length() > 0) {
            Spinner spinner = null;
            try {
                spinner = new Spinner();
                spinner.startSpinner();
            } catch (Exception ex) {
            }
            Scanner fileScanner = new Scanner(outputFile);
            fileScanner.nextLine();
            String separator = System.getProperty("line.separator");
            FileWriter fileStream = new FileWriter(outputFile);
            BufferedWriter out = new BufferedWriter(fileStream);
            while (fileScanner.hasNextLine()) {
                String next = fileScanner.nextLine();
                if (next.equals(separator)) {
                    out.newLine();
                } else {
                    out.write(next);
                }
                out.newLine();
            }
            out.close();
            if (spinner != null) {
                try {
                    Thread.sleep(5000);
                    spinner.stopSpinner(false);
                } catch (InterruptedException ex) {
                }
                
            }
        }
    }
}
